<?php

namespace app\controller\api;

use app\exception\ErrnoPlus;
use app\validate\QrcodeValidate;
use share\controller\ApiBaseController;
use share\exception\ApiException;
use share\service\ContextService;
use share\service\QrcodeService;

class QrcodeController extends ApiBaseController{

    protected $beforeActionList = [
        "checkSign",
    ];

    public function initValidate(){        
        $this->validate = new QrcodeValidate();
    }


    public function apply_action(){  
        $input = $this->check();
        $deviceInfo = $this->getDeviceInfo();
        $res = QrcodeService::apply($input,$deviceInfo);
        return self::ok($res);
    }
 
    public function info_action(){ 
        $input = $this->check();
        $deviceInfo = $this->getDeviceInfo();
        $input['deviceId'] = $deviceInfo['deviceId'];
        $res = QrcodeService::info($input['token'],$input); 
        if(empty($res)){ //已过期
            return self::ok([
                'token' => $input['token'],
                'status' => 0,
            ]);
        } 
        return self::ok($res);
    }

    public function getDeviceInfo(){
        $params = $this->request->param();
        $ip = ContextService::getIP();
        $vendor = ContextService::getVendor();
        $version = ContextService::getAppVersion();
        $clientType = ContextService::getClientType();
        $clientName = ContextService::getClientName();
        $packageName = ContextService::getPackageName();
        $deviceId = isset($params['deviceId']) ? $params['deviceId'] : ContextService::getDeviceId();
        if(empty($vendor)) {
            throw new ApiException("header vendor is require",ErrnoPlus::COMMON_INVALID_INPUT);
        }
     
        if(empty($deviceId)){
            throw new ApiException("deviceId is require",ErrnoPlus::COMMON_INVALID_INPUT);
        }
        $deviceInfo = [
            'ip' => $ip,
            'vendor' => $vendor,
            'version' => $version,
            'clientType' => $clientType,
            'clientName' => $clientName,
            'packageName' => $packageName,
            'deviceId' => $deviceId,
        ];
        return $deviceInfo;
    }
}